import { relationalStore } from '@kit.ArkData'
import { Context } from '@kit.AbilityKit'


export let db:relationalStore.RdbStore|undefined=undefined

export function init(context:Context){
  relationalStore.getRdbStore(context, {
    name: 'text.db',
    securityLevel: relationalStore.SecurityLevel.S2
  },(err,store)=>{
    if (err) {
      console.log(`创建数据可失败，错误码:${err.code},错误信息：${err.message}`)
      return
    }
    db=store
    if (db.version==0) {//从版本0升级到版本2
      db.executeSql('create table user(id integer primary key autoincrement, username text not null,password text not null,address text not null);')
        .then(()=>{
          console.log('创建成功')
            db!.version=1

        })
        .catch((e:Error)=>{
          console.log(`创建表失败，错误信息：${e.message}`)
        })
    }
    if (db.version==1) {
      db.executeSql('alter table user add column address text not null default "默认地址" ')
        .then(()=>{
          console.log(`升级数据库成功`)
          db!.version=2
        })
        .catch((e:Error)=>{
          console.log(`升级数据库失败，错误信息：${e.message}`)
        })
    }
    console.log('初始化完成')
  })

}
export function load<T>(pre:relationalStore.RdbPredicates):Promise<T[]>{
  return new Promise<T[]>((resole,reject)=> {
    db?.query(pre)
      .then((r) => {
        let temp: T[] = []
        let names = r.columnNames
        while (r.goToNextRow()) {
          let o = new Object()
          for (let i = 0; i < names.length; i++) {
            let name = names[i]
            {
                o[name] = r.getString(r.getColumnIndex(name))
            }
          }
          temp.push(o as T)
        }
        resole(temp)
      })
    .catch(e => reject(e))
 })
}